<?php if (!defined("_ECRIRE_INC_VERSION")) return;
/**
 * Aloha Cart
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage alohacart
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/AlohaCart
 */

/**
 *  Order form
 */ 

include_spip('classes/alohacart');

function formulaires_alohacart_order_charger_dist(){
	$valeurs = array();
	
	$valeurs['name'] = '';
    $valeurs['tel'] = '';
	$valeurs['mail'] = '';
    $valeurs['city'] = '';
    $valeurs['address'] = '';
    $valeurs['order_comments'] = '';
    
    $cart = new AlohaCart();
        
	return $valeurs;
}

function formulaires_alohacart_order_verifier_dist(){    
	$erreurs = array();
    
    // check that mandatory fields are indeed filled out:
    $mand_fields = array('name', 'tel', 'mail'); 
	foreach($mand_fields as $obligatoire)
		if (!_request($obligatoire)) $erreurs[$obligatoire] = _T('alohacart:obligatory_field');
		
	// check that any entered email address is correctly formatted:
	
    include_spip('inc/filtres');
	if (_request('mail') AND !email_valide(_request('mail')))
		$erreurs['mail'] = _T('alohacart:wrong_email');	
     
    if ($erreurs)
        $erreurs['message_erreur'] = _T('alohacart:form_error');
    
	return $erreurs;

}

function formulaires_alohacart_order_traiter_dist(){    
    if (!_request('url')) {
    $cart = new AlohaCart();
    // Admin will receive message in site's main language:
    $spip_lang = $GLOBALS['spip_lang'];
    $GLOBALS['spip_lang'] = $GLOBALS['meta']['langue_site'];
    
    // Send admin message:
    send_message_admin();
    
    // Log order:
    log_order();
    
    // Return curent language to the previous state:
    $GLOBALS['spip_lang'] = $spip_lang;
    
    // Send user email if needed:
    if (lire_config('alohacart/send_usr_email') and _request('mail')) {
        send_message_user();
    }    
    
    $cart->ClearCart();
    }
    return array('message_ok'=>_T('alohacart:your_order_accepted'));    
}

function send_message_admin() {
    $email_to = lire_config('alohacart/orders_emails');
    $header = 'MIME-Version: 1.0' . "\n" . 'Content-type: text/html; charset=UTF-8';
    $email_from = $GLOBALS['meta']['nom_site'];//'no-reply@'.$_SERVER['SERVER_NAME'];
    $header = $header."\n".'From: '.$email_from;
    $subject = '['.get_url_site().'] Новый заказ товара';//_T('alohacart:new_order');
       
    $message = "
    <html>
    <title>".$subject."</title>    
    <body>
    -------"._T('alohacart:user_data')."-------<br />        
    "._T('alohacart:name').": ".$_POST['name']."<br />
    "._T('alohacart:phone').": ".$_POST['tel']."<br />
    "._T('alohacart:email').": ".$_POST['mail']."<br />
    "._T('alohacart:city').": ".$_POST['city']."<br />
    "._T('alohacart:address').": ".$_POST['address']."<br />
    "._T('alohacart:order_comments').": ".$_POST['order_comments'];
    
    
    $cart = new AlohaCart();
    
    $message .= "<br />
    <br />
    -------"._T('alohacart:ordered_products')."-------";
    $products = $cart->GetProducts();
    foreach ($products as $product_id=>$product) {
        if ($product["link"]) {
            $link_pre = '<a href="'.$product["link"].'">';
            $link_post = '</a>';
        } else {$link_pre = ''; $link_post = '';}
        $message .= "<br />
    ".$product["article"].' - '.$link_pre.$product["titre"].$link_post." (".$product["quantity"]." "._T('alohacart:pcs').") - ".$product["price"]." "._T('alohacart:local_currency');
    }
    
    $cart_quantity = $cart->CountProducts();
    $cart_price = $cart->CountPrice();
    
    $message .= "<br />    
    "._T('alohacart:total_products_quantity').": ".$cart_quantity." "._T('alohacart:pcs')."<br />
    "._T('alohacart:total_price').": ".$cart_price." "._T('alohacart:local_currency');
     
    $message .= "<br />
    <br />
    -------"._T('alohacart:ga_visitor_info')."-------<br />
    "._T('alohacart:ga_source').":    ".$_REQUEST['source']."<br />
    "._T('alohacart:ga_medium').": ".$_REQUEST['medium']."<br />
    "._T('alohacart:ga_term').":       ".$_REQUEST['term']."<br />
    "._T('alohacart:ga_content').":  ".$_REQUEST['content']."<br />
    "._T('alohacart:ga_campaign').":    ".$_REQUEST['campaign']."<br />
    "._T('alohacart:ga_segment').":     ".$_REQUEST['segment'];
    
    $message .= '</body></html>';
    if ($email_to)        
        mail($email_to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $header);
}

function send_message_user() {
    $email_to = _request('mail');
    $header = 'MIME-Version: 1.0' . "\n" . 'Content-type: text/html; charset=UTF-8';
    $email_from = $GLOBALS['meta']['nom_site'];
    $header = $header."\n".'From: '.$email_from;
    $subject = '['.get_url_site().'] Ваш заказ принят.';//_T('alohacart:order_accepted');
    
    $message = _T('alohacart:your_order_accepted')."<br />"._T('alohacart:order_info').":<br />";   
    $message .= "<br />
    -------"._T('alohacart:user_data')."-------<br />        
    "._T('alohacart:name').": ".$_POST['name']."<br />
    "._T('alohacart:phone').": ".$_POST['tel']."<br />
    "._T('alohacart:email').": ".$_POST['mail']."<br />
    "._T('alohacart:city').": ".$_POST['city']."<br />
    "._T('alohacart:address').": ".$_POST['address']."<br />
    "._T('alohacart:order_comments').": ".$_POST['order_comments'];
    
    $cart = new AlohaCart();
    
    $message .= "<br />
    <br />
    -------"._T('alohacart:ordered_products')."-------";
    $products = $cart->GetProducts();
    foreach ($products as $product_id=>$product) {
        if ($product["link"]) {
            $link_pre = '<a href="'.$product["link"].'">';
            $link_post = '</a>';
        } else {$link_pre = ''; $link_post = '';}
        $message .= "<br />
    ".$product["article"].' - '.$link_pre.$product["titre"].$link_post." (".$product["quantity"]." "._T('alohacart:pcs').") - ".$product["price"]." "._T('alohacart:local_currency');
    }
    
    $cart_quantity = $cart->CountProducts();
    $cart_price = $cart->CountPrice();
    
    $message .= "<br />    
    "._T('alohacart:total_products_quantity').": ".$cart_quantity." "._T('alohacart:pcs')."<br />
    "._T('alohacart:total_price').": ".$cart_price." "._T('alohacart:local_currency');
    
    if ($email_to)        
        mail($email_to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $header);
}

function log_order() {
    // Check htaccess
    check_htaccess();
    $cart = new AlohaCart();
    $file_name = find_in_path('alohacart_logs/orders.csv');
    if (!$file_name) $file_name = _DIR_PLUGIN_ALOHACART.'alohacart_logs/orders.csv';
    $content = false;
    if (file_exists($file_name))
        $content = file_get_contents($file_name);
    if (!$content)
        file_put_contents($file_name,
            _T('alohacart:shop').";". 
            _T('alohacart:date').";".            
            _T('alohacart:article').";".
            _T('alohacart:titre').";".
            _T('alohacart:quantity').";".
            _T('alohacart:cost').";".
            _T('alohacart:customer').";".
            _T('alohacart:phone').";".
            _T('alohacart:email').";".
            _T('alohacart:city').";".
            _T('alohacart:address').";".            
            _T('alohacart:ga_source').";".
            _T('alohacart:ga_medium').";".
            _T('alohacart:ga_term').";".
            _T('alohacart:ga_content').";".
            _T('alohacart:ga_campaign').";".PHP_EOL, FILE_APPEND);
    $products = $cart->GetProducts();
    foreach ($products as $product_id=>$product) {
        file_put_contents($file_name,
            get_url_site().";". 
            date('d/n/Y H:i:s').";".            
            $product["article"].";".
            $product["titre"].";".
            $product["quantity"].";".
            $product["price"].";".
            _request('name').";".
            _request('tel').";".
            _request('mail').";".
            _request('city').";".
            _request('address').";".            
            _request('source').";".
            _request('medium').";".
            _request('term').";".
            _request('content').";".
            _request('campaign').PHP_EOL, FILE_APPEND);
    }
}

function get_url_site(){
    $url = $GLOBALS['meta']['adresse_site'];
    $url = str_replace('http://','',$url);
    $url = str_replace('www.','',$url);
    return $url; 
} 

/**
 *  Checks whether .htaccess file in alohacart_logs orders exists
 *  and creates it if not
 */
function check_htaccess() {
    $file_name = find_in_path('alohacart_logs/.htaccess');
    if (!$file_name) $file_name = _DIR_PLUGIN_ALOHACART.'alohacart_logs/.htaccess';
    $content = '
    <Files orders.csv>
    order allow,deny
    deny from all
    </Files>';    
    if (!file_exists($file_name)) {
        file_put_contents($file_name, $content);
    } 
} 

?>